package com.icinfo.cloud.provider.punish.common.caseregister.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.exception.SignBusinessException;
import com.icinfo.cloud.provider.common.qr.service.IQrService;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.common.utils.HeaderUtil;
import com.icinfo.cloud.provider.peripheralinterface.xzzf.dto.ZfPeopleDataDto;
import com.icinfo.cloud.provider.peripheralinterface.xzzf.service.IXzzfInterfaceService;
import com.icinfo.cloud.provider.punish.common.caseregister.service.IRegisterCommonService;
import com.icinfo.cloud.provider.punish.config.mapper.SysAreaMapper;
import com.icinfo.cloud.provider.punish.config.mapper.SysDepartParamMapper;
import com.icinfo.cloud.provider.punish.config.model.SysArea;
import com.icinfo.cloud.provider.punish.config.model.SysDepartParam;
import com.icinfo.cloud.provider.punish.config.service.ISysDepartParamService;
import com.icinfo.cloud.provider.punish.config.vo.AreaVo;
import com.icinfo.cloud.provider.punish.config.vo.LineCaseHandleInfoVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseMainDetailInfoService;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.PersonInfoMsgVo;
import com.icinfo.cloud.provider.punish.ucase.caseregister.dto.CaseLineInfoQueryDto;
import com.icinfo.cloud.provider.punish.ucase.caseregister.dto.RealNameCheckDto;
import com.icinfo.cloud.provider.punish.ucase.caseregister.enums.RealNameCheckResultEnum;
import com.icinfo.cloud.provider.punish.ucase.caseregister.vo.CaseLineInfoVo;
import com.icinfo.cloud.provider.punish.ucase.caseregister.vo.RealNameCheckVo;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.vo.CasePartyNoticeVo;
import com.icinfo.cloud.provider.punish.usersign.service.IMemberUserSignService;
import com.icinfo.cloud.xzcf.provider.member.org.dto.Org;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lxj
 * @date 2022/3/2
 **/
@Slf4j
@Service
public class IRegisterCommonServiceImpl implements IRegisterCommonService {

//    @Value("${sendOrgUrl}")
//    private String sendOrgUrl;
    @Value("${member.url}")
    private String memberUrl;
    @Value("${member.api.getOrgByOrgCode}")
    private String getOrgByOrgCode;
    @Value("${tzxzcfUrl}")
    private String tzxzcfUrl;
    @Resource
    private ICaseMainDetailInfoService caseMainDetailInfoService;
    @Resource
    private SysAreaMapper sysAreaMapper;
    @Resource
    SysDepartParamMapper sysDepartParamMapper;
    @Resource
    private ISysDepartParamService sysDepartParamService;
    @Resource
    private IXzzfInterfaceService xzzfInterfaceService;
    @Resource
    private IMemberUserSignService memberUserSignService;
    @Value("${isCheckHandleSign}")
    private String isCheckHandleSign;
    @Value("${realNameCheck.secret}")
    private String realNameCheckSecret;
    @Value("${realNameCheck.url}")
    private String realNameCheckUrl;

    @Resource
    private IQrService iQrService;

    /**
     * 获取登录用户单位信息
     *
     * @return Result
     * @author lxj
     * @date 2022/2/23
     **/
    @Override
    public Org getUserOrgMsg() {
        try {
            UserDTO userDTO = UserUtil.getUserInfo();
            if (ObjectUtils.isEmpty(userDTO) || StringUtils.isEmpty(userDTO.getOrgCode())){
                return null;
            }
            Map<String, String> headers = HeaderUtil.headerInfo();
            String url = memberUrl + getOrgByOrgCode + "?orgCode=" + userDTO.getOrgCode();
            String response = HttpUtil.createGet(url).addHeaders(headers).execute().body();
            if (StringUtils.isNotEmpty(response)) {
                return JSONObject.parseObject(response, Org.class);
            }
            return null;
        } catch (Exception e) {
            log.warn(e.getMessage());
            return null;
        }
    }

    /**
     * 获取案件办案人员信息（主办+协办），办案人签名
     *
     * @param caseId
     * @return
     * @author lxj
     * @date 2022/3/4
     **/
    @Override
    public CasePartyNoticeVo getCaseHandleAndSignMsg(String caseId) {
        CasePartyNoticeVo vo = caseMainDetailInfoService.getNoticeMsg(caseId, null);
        if (vo == null) {
            return null;
        }
        return vo;
    }

    /**
     * 获取办案用户签名接口--外部
     * 一定要有token在请求头里面
     *
     * @author lxj
     */
    @Override
    public String getHandleSignData(String userId) {
        //改造成统一调用大综合获取签名接口--20220830
        try {
            ZfPeopleDataDto dto = xzzfInterfaceService.getZfPeopleSignDataByUserInfo(userId);
            if (!ObjectUtils.isEmpty(dto) && !ObjectUtils.isEmpty(dto.getSignData())) {
                //签名base64优化为文件地址 -- 20230522
                return iQrService.base64ToOssUrl(dto.getSignData());
                //return "data:image/jpg;base64," + dto.getSignData();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if ("true".equals(isCheckHandleSign)) {
            throw new SignBusinessException("用户签名信息不存在，需至掌上执法-我的-我的签名，进行设置");
        } else {
            return "";
        }

        /*try {
            //todo
            JSONObject json = new JSONObject();
            json.put("type", 1);
            json.put("userId", userId);
            String url = tzxzcfUrl + "/api/v2/member/user/sealInfo";
            Map<String, String> headers = HeaderUtil.headerInfo();
            String param = json.toJSONString();
            String response = HttpUtil.createPost(url).addHeaders(headers).body(param).execute().body();
            if (StringUtils.isNotEmpty(response)) {
                JSONObject jsonObject = JSONObject.parseObject(response);
                String code = jsonObject.getString("code");
                if ("200".equals(code)) {
                    return "data:image/jpg;base64," + jsonObject.getString("data");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            *//*if ("true".equals(isCheckHandleSign)) {
                throw new BusinessException("获取用户签名信息异常！请稍后再试");
            } else {
                return "";
            }*//*
        }

        //增加查询本地设置签名表
        MemberUserSign memberUserSign = memberUserSignService.selectUserSign(userId);
        if (!ObjectUtils.isEmpty(memberUserSign) && !ObjectUtils.isEmpty(memberUserSign.getUserSignUrl())) {
            InputStream is = HttpUtil.createGet(memberUserSign.getUserSignUrl()).execute().bodyStream();
            // 文件转为base64
            return "data:image/jpg;base64," + Base64.encode(is);
        }*/
    }

    /**
     * 获取当事人的身份信息-通过身份证
     *
     * @param idCard
     * @return
     * @author lxj
     * @date 2022/3/17
     **/
    @Override
    public PersonInfoMsgVo getPersonInfoByIdCard(String idCard) {
        //本地调用需注释下面地址
        //String url = "https://eshare.tzzhcg.com:7443/api/v1/cevidence/api/dataSharing/getIdCardInfo";
        String url ="http://10.145.147.112:8581/proxy/sfzAddr/api/v1/cevidence/api/dataSharing/getIdCardInfo";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("idCard", idCard);
        String ret = BaseUtil.post(url, jsonObject);
        JSONObject retJson = JSONObject.parseObject(ret);
        if (Constant.INTEGER_200.equals(retJson.getInteger("code"))) {
            PersonInfoMsgVo personInfoMsgVo = JSONObject.toJavaObject(retJson.getJSONObject("data"), PersonInfoMsgVo.class);
            JSONObject addressInfo= BaseUtil.resolutionAddress(personInfoMsgVo.getAddress());
            // 省公安接口未返回区划信息，手动解析区划信息
            if (ObjectUtil.isNotEmpty(addressInfo)){
                personInfoMsgVo.setAddressDetail(addressInfo.getString("detail"));
                String[] details = addressInfo.getJSONArray("addressAreas").toJavaObject(String[].class);
                personInfoMsgVo.setAddressAreas(details);
            }
            return personInfoMsgVo;
        }
        return null;
    }

    /**
     * 获取区划
     *
     * @return
     * @author lxj
     * @date 2022/3/21
     **/
    @Override
    public List<AreaVo> getSysAreaList() {
        //获取省级区域
        Example proExample = new Example(SysArea.class);
        proExample.createCriteria().andEqualTo("isDel", Constant.STRING_0).andEqualTo("level", Constant.STRING_1);
        List<SysArea> provinceList = sysAreaMapper.selectByExample(proExample);


        Example cityExample = new Example(SysArea.class);
        cityExample.createCriteria().andEqualTo("isDel", Constant.STRING_0).andEqualTo("level", Constant.STRING_2);
        List<SysArea> cityList = sysAreaMapper.selectByExample(cityExample);

        //获取区级区域
        Example areaExample = new Example(SysArea.class);
        areaExample.createCriteria().andEqualTo("isDel", Constant.STRING_0).andEqualTo("level", Constant.STRING_3);
        List<SysArea> areaList = sysAreaMapper.selectByExample(areaExample);


        List<AreaVo> list = new ArrayList<>();
        for (int i = 0; i < provinceList.size(); i++) {
            List<AreaVo> cList = new ArrayList<>();
            for (int j = 0; j < cityList.size(); j++) {
                if (provinceList.get(i).getAreaCode().equals(cityList.get(j).getParentAreaCode())) {
                    List<AreaVo> aList = new ArrayList<>();
                    for (int k = 0; k < areaList.size(); k++) {
                        if (cityList.get(j).getAreaCode().equals(areaList.get(k).getParentAreaCode())) {
                            AreaVo aVo = new AreaVo();
                            aVo.setAreaCode(areaList.get(k).getAreaCode());
                            aVo.setAreaName(areaList.get(k).getAreaName());
                            aVo.setLevel(areaList.get(k).getLevel());
                            aList.add(aVo);
                        }
                    }
                    AreaVo cVo = new AreaVo();
                    cVo.setList(aList);
                    cVo.setAreaCode(cityList.get(j).getAreaCode());
                    cVo.setAreaName(cityList.get(j).getAreaName());
                    cVo.setLevel(cityList.get(j).getLevel());
                    cList.add(cVo);
                }
            }
            AreaVo proVo = new AreaVo();
            proVo.setLevel(provinceList.get(i).getLevel());
            proVo.setAreaCode(provinceList.get(i).getAreaCode());
            proVo.setAreaName(provinceList.get(i).getAreaName());
            proVo.setList(cList);
            list.add(proVo);
        }

        return list;
    }

    /**
     * 获取文书抬头
     *
     * @return
     * @author lxj
     * @date 2022/3/31
     **/
    @Override
    public String getOrgStandardNameByOrgCode(String orgCode,String deptCode) {
        String orgStandardName="";
        /*Example example = new Example(SysDepartParam.class);
        example.createCriteria().andEqualTo("orgCode", orgCode);
        List<SysDepartParam> list = sysDepartParamMapper.selectByExample(example);
        if (list != null && list.size() > 0) {
            return list.get(0).getOrgStandardName();
        }*/
        SysDepartParam sysDepartParam =sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(orgCode,deptCode);
        if(null!=sysDepartParam){
            orgStandardName=sysDepartParam.getOrgStandardName();
            return orgStandardName;
        }
        return null;
    }

    /**
     * 通过参数获取法人库信息
     *
     * @param uniscid 统一代码
     * @param company 公司名称
     * @return
     * @author lxj
     */
    @Override
    public JSONArray getCompanyMsg(String uniscid, String company) {

        String url = "http://59.202.52.139:8082/frk/api/getqyjbxx";
        Map<String, String> map = new HashMap<>(4);
        map.put("tyxydm", uniscid);
        map.put("frmc", company);
        String response = BaseUtil.sendGETRequest(url, map);
        log.info("==========" + response);
        if (StringUtils.isEmpty(response)) {
            return null;
        }
        JSONObject jsonObject = JSONObject.parseObject(response);
        if (jsonObject.getString("code").equals("00")) {
            JSONArray array = jsonObject.getJSONArray("result");
            if (array != null && array.size() > 0) {
                return array;
            }
        }
        return null;
    }

    @Override
    public RealNameCheckVo checkRealName(RealNameCheckDto checkDto) {
        try {
            /*JSONObject paramJson = new JSONObject();
            paramJson.put("idCard", checkDto.getIdCard());
            paramJson.put("realName", checkDto.getRealName());
            paramJson.put("secretkey", Md5Util.md5(realNameCheckSecret + checkDto.getIdCard()));
            String result = BaseUtil.post(realNameCheckUrl, paramJson);
            log.info("调取实名认证结果-----:" + result);
            JSONObject retJson = JSONObject.parseObject(result);
            RealNameCheckVo realNameCheckVo = new RealNameCheckVo();
            if (retJson.getString("status").equals((Constant.STRING_SUCCESS_EN))) {
                JSONObject js = retJson.getJSONObject("data");
                //获取身份证编码
                if (ObjectUtil.isEmpty(js.get("shenfzbs"))) {
                    realNameCheckVo.setRealNameCheckResultCode(RealNameCheckResultEnum.CHECK_NO_DATA.getCode());
                } else {
                    realNameCheckVo.setRealNameCheckResultCode(js.getString("shenfzbs"));
                }
            } else {
                realNameCheckVo.setRealNameCheckResultCode(RealNameCheckResultEnum.CHECK_FAIL.getCode());
            }
            realNameCheckVo.setRealNameCheckResultDes(RealNameCheckResultEnum.getValueByCode(realNameCheckVo.getRealNameCheckResultCode()));
            */
            RealNameCheckVo realNameCheckVo = new RealNameCheckVo();
            realNameCheckVo.setRealNameCheckResultCode(RealNameCheckResultEnum.CHECK_SAME.getCode());
            realNameCheckVo.setRealNameCheckResultDes("校验一致");
            return realNameCheckVo;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public boolean checkRealNameDifferent(String idCard, String realName) {
        boolean flag = false;
        RealNameCheckDto checkDto = new RealNameCheckDto();
        checkDto.setIdCard(idCard);
        checkDto.setRealName(realName);
        RealNameCheckVo realNameCheckVo = checkRealName(checkDto);
        if (RealNameCheckResultEnum.CHECK_DIFFERENT.getCode().equals(realNameCheckVo.getRealNameCheckResultCode())) {
            flag = true;
        }
        return flag;
    }

    @Override
    public List<CaseLineInfoVo> getCaseLineIInfoList(CaseLineInfoQueryDto queryDto) {
        UserDTO userInfo = UserUtil.getUserInfo();
        if (ObjectUtil.isEmpty(userInfo)){
            throw  new BusinessException("登录失效");
        }
        //获取办案单位参数
        SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCode(userInfo.getOrgCode(),userInfo.getDeptCode());
        if (ObjectUtil.isEmpty(sysDepartParam.getLineConfig())){
            throw  new BusinessException("办案机构暂未配置条线信息，请联系管理员");
        }
        //将条线配置组装成集合对象
        List<LineCaseHandleInfoVo> lineCaseHandleInfoVos = sysDepartParamService.assembleLineConfigToList(sysDepartParam.getLineConfig());
       //int lineSize= lineCaseHandleInfoVos.size();
        List<CaseLineInfoVo> caseLineInfoVos = new ArrayList<>();
        for (LineCaseHandleInfoVo lineCaseHandleInfoVo:lineCaseHandleInfoVos) {
            CaseLineInfoVo caseLineInfoVo = new CaseLineInfoVo();
            if(!Constant.STRING_1.equals(lineCaseHandleInfoVo.getLineCaseHandleStatusCode())){
                continue;
            }
            caseLineInfoVo.setLineCode(lineCaseHandleInfoVo.getLineCode());
            caseLineInfoVo.setLineName(lineCaseHandleInfoVo.getLineName());
            caseLineInfoVo.setAlineCseHandleStatusCode(lineCaseHandleInfoVo.getLineCaseHandleStatusCode());
            caseLineInfoVos.add(caseLineInfoVo);
        }
        /*List<CaseLineInfoVo>  caseReasonLineList=new ArrayList<>();
        List<String>  territoryCodes= queryDto.getCaseReasonInfoList().stream().map(CaseReasonInfoDto::getTerritoryCode).distinct().collect(Collectors.toList());
        for (int i=0;i<lineSize;i++) {
            if (Constant.STRING_1.equals(lineCaseHandleInfoVos.get(i).getLineCaseHandleStatusCode())) {
                CaseLineInfoVo caseLineInfoVo = new CaseLineInfoVo();
                caseLineInfoVo.setLineCode(lineCaseHandleInfoVos.get(i).getLineCode());
                caseLineInfoVo.setLineName(lineCaseHandleInfoVos.get(i).getLineName());
                caseLineInfoVo.setAlineCseHandleStatusCode(lineCaseHandleInfoVos.get(i).getLineCaseHandleStatusCode());
                //只有一个案由和条线进行比对
                if (territoryCodes.size()==1) {
                    LineDTO lineDto = xzzfInterfaceService.getLineInfoByLineCode(caseLineInfoVo.getLineCode());
                    if (territoryCodes.get(0).equals(lineDto.getTerritoryCode())){
                        caseReasonLineList.add(caseLineInfoVo);
                        caseLineInfoVos=caseReasonLineList;
                        break;
                    }
                }
                caseLineInfoVos.add(caseLineInfoVo);
            }
        }*/
        return caseLineInfoVos;
    }

}
